<?php

namespace app\models;

use Yii;

/**
 * This is the model class for table "auth_item_child".
 *
 * @property string $parent
 * @property string $child
 *
 * @property AuthItem $parent0
 * @property AuthItem $child0
 */
class Role extends \yii\db\ActiveRecord
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%auth_item}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            ['name','required','on'=>['create','edit']],
            ['name','string','max'=>20,'on'=>['create','edit']],
            ['name','unique','on'=>['create']],
            ['name','unique','on'=>['edit'],'filter'=>['<>','name',$this->name]],

            ['description','required','on'=>['create','edit']],
            ['description','string','max'=>100,'on'=>['create','edit']],

            ['rule_name','safe'],

            ['data','safe'],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'name' => '角色标识',
            'description' => '角色名称',
            'rule_name' => '规则名称',
            'data' => '数据',
        ];
    }

    public function createRole()
    {
        if ($this->validate()){
            $auth = Yii::$app->authManager;
            $role = $auth->createRole($this->name);
            $role->description = $this->description;
            if ($auth->add($role)){
                return true;
            }
        }
        return false;
    }

    public function editRole()
    {
        if ($this->validate()){
            $auth = Yii::$app->authManager;
            $role = $auth->createRole($this->name);
            $role->description = $this->description;
            if ($auth->update($this->getOldAttribute('name'),$role)){
                return true;
            }
        }
        return false;
    }


}
